import Link from "next/link"
"use client"; // 添加这行作为文件的第一行
import { useState, useRef, ChangeEvent } from "react";

export default function CertificatesPage() {
  const [showModal, setShowModal] = useState(false);
  const [modalMessage, setModalMessage] = useState("");
  const [countdown, setCountdown] = useState(0); // 验证码倒计时
  const [verificationCode, setVerificationCode] = useState(""); // 验证码输入值


  const showErrorModal = (message: string) => {
    setModalMessage(message);
    setShowModal(true);
  };

  const [formData, setFormData] = useState({
    name: "",
    telephone: "",
    idnumber: "",
    password: "",
    code:"",
  });
  
  // 发送验证码
  const sendVerificationCode = async () => {
    if (!formData.telephone) {
      showErrorModal("请输入手机号码");
      return;
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.telephone)) {
      showErrorModal("请输入正确的手机号码");
      return;
    }

    try {
      // 设置倒计时60秒
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) clearInterval(timer);
          return prev - 1;
        });
      }, 1000);

      // 调用发送验证码接口
      const response = await fetch('http://192.168.1.219:8080/sms/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          phone: formData.telephone,
          type: "register" // 注册类型
        }),
      });

      if (!response.ok) {
        throw new Error('发送验证码失败');
      }

      showErrorModal("验证码已发送");
    } catch (error) {
      showErrorModal("发送验证码失败，请重试");
      }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target;
    setFormData(prev => ({ ...prev, [id]: value }));

  };

  const handleSave = async (e: React.FormEvent, action: "save" | "update") => {
    e.preventDefault();
    // 验证验证码
    if (!formData.code) {
      showErrorModal("请输入验证码");
      return;
    }

    try {
      const response = await fetch('http://192.168.1.219:8080/student/add', {
        method: 'POST',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        throw new Error('网络响应异常');
      }
  
      // 3. 处理成功响应
      const result = await response.json();
      showErrorModal('注册成功！');
      console.log('操作成功:', result);

    } catch (error) {
      // 4. 处理错误
      const message = error instanceof Error ? error.message : '操作失败，请重试';
      showErrorModal(message);
      console.error('操作出错:', error);
    }
  };

  return (
    <main className="min-h-screen">
   
      <section className="py-20 pt-8">
        {/* 设置并列布局grid grid-cols-2 gap-8 */}
        <div className="container mx-auto px-4 ">
          {/* <div className="max-w-3xl mx-auto"> */}
          <div className="max-w-3xl mx-auto">
            <div className="bg-white rounded-lg shadow-sm p-8">
              {/* <h2 className="text-2xl font-bold mb-6">注册</h2> */}
              <form className="space-y-6">
                {/* <div className="flex items-center">
                  <label htmlFor="certificate-number" className="block text-sm font-medium mb-2 mr-4">
                    姓&emsp;&nbsp;名<span className="text-red-600">*</span> &nbsp;&nbsp; &emsp;&nbsp;
                  </label>
                  <input 
                    type="name"
                    id="certificate-number"
                    className="flex-grow px-4 py-2 border rounded-md"
                    placeholder="请输入姓名"
                    required //必填项
                    onChange={handleInputChange} // 添加这行
                    value={formData.name}    // 添加这行
                  />
                </div> */}
                {/* <div className="flex items-center">
                  <label htmlFor="name" className="block text-sm font-medium mb-2 mr-4">
                    身份证号 <span className="text-red-600">*</span>&emsp; &nbsp;
                  </label>
                  <input
                    type="text"
                    id="idnumber"
                    className="flex-grow px-4 py-2 border rounded-md"
                    placeholder="请输入身份证号"
                    required
                    onChange={handleInputChange} // 添加这行
                    value={formData.idnumber}    // 添加这行
                  />
                </div> */}
                <div className="flex items-center">
                  <label htmlFor="name" className="block text-sm font-medium mb-2 mr-4">
                    联系电话 <span className="text-red-600">*</span>&emsp; &nbsp;
                  </label>
                  <input
                    type="text"
                    id="telephone"
                    className=" px-4 py-2 border rounded-md flex-grow"
                    placeholder="请输入联系电话"
                    required
                    onChange={handleInputChange} // 添加这行
                    value={formData.telephone}    // 添加这行
                  />
                </div>
                {/* <div className="flex items-center">
                  <label htmlFor="name" className="block text-sm font-medium mb-2 mr-4">
                    密&emsp;&nbsp;&nbsp;&nbsp;码 <span className="text-red-600">*</span>&emsp; &nbsp;
                  </label>
                  <input
                    type="password"
                    id="password"
                    className=" px-4 py-2 border rounded-md flex-grow"
                    placeholder="请输入联系电话"
                    required
                    onChange={handleInputChange} // 添加这行
                    value={formData.password}    // 添加这行
                  />
                </div> */}

                 {/* 新增验证码输入框和发送按钮 */}
                 <div className="flex items-center">
                  <label htmlFor="code" className="block text-sm font-medium mb-2 mr-4">
                    验证码 <span className="text-red-600">*</span>&emsp; &nbsp;&emsp;
                  </label>
                  <div className="flex flex-grow gap-2">
                    <input
                      type="text"
                      id="code"
                      className="px-4 py-2 border rounded-md flex-1"
                      placeholder="请输入验证码"
                      required
                      onChange={handleInputChange}
                      value={formData.code}
                      maxLength={6}
                    />
                    <button
                      type="button"
                      onClick={sendVerificationCode}
                      disabled={countdown > 0}
                      className={`px-4 py-2 rounded-md ${countdown > 0 
                        ? 'bg-gray-300 text-gray-500' 
                        : 'bg-blue-600 text-white hover:bg-blue-700'}`}
                    >
                      {countdown > 0 ? `${countdown}秒后重发` : '获取验证码'}
                    </button>
                  </div>
                </div>

               <div className="flex">
                <button type="submit" className="w-full bg-primary text-white py-2 rounded-md hover:bg-primary/90 mr-2">
                  登录
                </button>
                <button type="submit" className="w-full bg-primary text-white py-2 rounded-md hover:bg-primary/90">
                  注册
                </button>
              </div>
              </form>
            </div>
          </div>
          
        </div>
      </section>

      {/* <section className="py-20 bg-gray-50">
        <div className="container mx-auto px-4">
          <h2 className="text-3xl font-bold text-center mb-12">证书说明</h2>
          <div className="grid md:grid-cols-3 gap-8">
            {[
              {
                title: "权威认证",
                content: "由政府机构认证，具有广泛认可度",
              },
              {
                title: "终身有效",
                content: "证书终身有效，可在线查询验证",
              },
              {
                title: "就业保障",
                content: "与多家机构合作，提供就业推荐",
              },
            ].map((item, index) => (
              <div key={index} className="text-center">
                <h3 className="text-xl font-bold mb-4">{item.title}</h3>
                <p className="text-gray-600">{item.content}</p>
              </div>
            ))}
          </div>
        </div>
      </section> */}
    </main>
  )
}

